# -*- coding: utf-8 -*-
"""
# 使用了 [numpy==1.24.4]，遵循其 [BSD-3-Clause] 许可证，原始代码来源：[https://www.numpy.org]
# 使用了 [pandas==2.0.3]，遵循其 [BSD 3-Clause License] 许可证，原始代码来源：[https://pandas.pydata.org]
"""
import sys
from pathlib import Path
import pandas as pd
import numpy as np
class PARA_CONFIG:
    CURRENT_DIR=Path(__file__).parent.resolve()
    KMEANS_PATH=CURRENT_DIR.parent.parent.resolve()/"03_kmeans"/"src"/"result"/"5_Kmeans_SK_01_kmeans_20251031_150848.xlsx"
    FCHECK_PATH=CURRENT_DIR.parent.parent.resolve()/"04_fcheck"/"src"/"result"/"6_F_check_SK_01_f_check_20251031_151220.xlsx"
    KEYS_PATH=CURRENT_DIR.parent.parent.resolve()/"02_lda"/"src"/"result"/"3_LDA_Keyword_Allocation_01_SK_LDA_20251031_143526.xlsx"
    FUNC_PATH=CURRENT_DIR.parent.parent.resolve()/"about_file"
sys.path.append(str(PARA_CONFIG.FUNC_PATH))
import f_basic

@f_basic.Timer
def print_topic(fp_k_allocation,cnt_words,topics_to_print):
    """Print Top words."""
    df=pd.read_excel(fp_k_allocation)
    feature=df.columns.values.tolist()
    key_allocation_array=np.array(df.values.tolist())
    for index,topic in enumerate(key_allocation_array):
        if(index in topics_to_print):
            print("Topic #%d:"%index)
            li_topic_words=[feature[i] for i in topic.argsort()[:-cnt_words-1:-1]]
            print(li_topic_words)

def normalize_columns_to_percentage(data_array):
    arr=np.array(data_array,dtype=float)
    col_sums=arr.sum(axis=0,keepdims=True)
    col_sums[col_sums==0]=1
    normalized=(arr/col_sums)*100
    return normalized

def find_max(data,thres=50):
    positions=np.argwhere(data>thres)
    return(positions)

if __name__ == "__main__":

    df_k=pd.read_excel(PARA_CONFIG.KMEANS_PATH)
    df_k.columns=["T#"+str(col) for col in df_k.columns]
    df_k=df_k.rename(columns={"T#label":"label"})
    df_f=pd.read_excel(PARA_CONFIG.FCHECK_PATH)
    li_topics=df_f["Topic"].values.tolist()#get the significant topic list.
    li_info=['label']
    li_topics.extend(li_info)
    li_cluster_label=sorted(df_k['label'].unique())
    cnt_cluster_labels=len(li_cluster_label)
    li_means=[]
    for cluster_label in li_cluster_label:
        df_obj=(df_k.query("label==@cluster_label")[li_topics].drop(columns=["label"],errors='ignore'))
        li_obj=df_obj.mean(skipna=True,axis=0).tolist()
        li_means.append(li_obj)
    np_means=normalize_columns_to_percentage(li_means)
    li_max=find_max(np_means)
    categories = np.unique(li_max[:, 0])
    result = {}
    for cat in categories:
        second_values=li_max[li_max[:,0]==cat][:,1]
        result[cat]=second_values
    for cat, values in result.items():
        print(f"聚类#{cat}:")
        print_topic(PARA_CONFIG.KEYS_PATH,6,values.tolist())